<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="../Css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="../Css/bootstrap-responsive.css" />
    <link rel="stylesheet" type="text/css" href="../Css/style.css" />
    <script type="text/javascript" src="../Js/jquery.js"></script>
    <script type="text/javascript" src="../Js/bootstrap.js"></script>
    <script type="text/javascript" src="../Js/ckform.js"></script>
    <script type="text/javascript" src="../Js/common.js"></script>

    <style type="text/css">
        body {
            padding-bottom: 40px;
        }
        .sidebar-nav {
            padding: 9px 0;
        }

        @media (max-width: 980px) {
            /* Enable use of floated navbar text */
            .navbar-text.pull-right {
                float: none;
                padding-left: 5px;
                padding-right: 5px;
            }
        }
        .warning{
            border-color: red !important;
        }

    </style>
</head>
<body>
<form class="definewidth m20">
    <table class="table table-bordered table-hover definewidth m10">
        <tr>
            <td width="10%" class="tableleft">角色名称</td>
            <td><input type="text" onblur="roleNameCheck(this.value)" name="rName"/></td>
        </tr>
        <tr>
            <td class="tableleft">状态</td>
            <td>
                <input type="radio" name="rState" value="0" checked/> 启用  <input type="radio" name="rState" value="1"/> 禁用
            </td>
        </tr>
        <tr>
            <td class="tableleft">权限</td>
            <td id="my-con">

            </td>
        </tr>
        <tr>
            <td class="tableleft"></td>
            <td>
                <button class="btn btn-primary" onclick="addRole()" id="role-add-btn" type="button">保存</button> &nbsp;&nbsp;<button type="button" class="btn btn-success" name="backid" id="backid">返回列表</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>
<script>

    // 设置定时器, 防止onblur和onclick发生冲突, 确保onclick先执行
    let roleNameCheckTime;
    // 发送添加标志,一旦发送即锁死,防止多次添加
    let sendAddFlag = true;
    // 角色名唯一性,非空检测标志
    let roleNameCheckFlag = false;
    // 角色名唯一性,非空检测
    function roleNameCheck(rName){
        roleNameCheckTime = setTimeout(function(){
            if(rName == null || rName == "" || rName == undefined){
                layer.msg("角色名不能为空", function(){})
                $("input[name='rName']").addClass("warning")
            }else{
                $.ajax({
                    type: "GET",
                    url: origin + "/role/r-name/" + rName,
					xhrFields: {
					   withCredentials: true
					},
					crossDomain: true,
                    data: {jwtToken:jwtToken},
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        if (data.code == 200){
                            roleNameCheckFlag = true;
                            $("input[name='rName']").removeClass("warning")
                        }else{
                            layer.msg("角色已存在，请重新输入。", function(){})
                            roleNameCheckFlag = false;
                            $("input[name='rName']").addClass("warning")
                        }
                    }
                    // TODO: 后端拦截ajax请求进行登陆跳转需要前端相互配合, 每一个ajax请求都需要加上以下的代码
                    ,complete : function(xhr, status) {
                        myComplete(xhr, status);
                    }
                })
            }
        },120)
    }
    // 查询所有资源信息,遍历生成列表
    function queryMenuList(){
        layer.load(0)
        $.ajax({
            type: "GET",
            url: origin + "/menu/list",
			xhrFields: {
			   withCredentials: true
			},
			crossDomain: true,
            data: {pageSize:999,pageNum:1,jwtToken:jwtToken},
            dataType: "json",
            success: function (data) {
                layer.closeAll()
                if (data.code == 200){
                    $.each(data.obj.list, function () {
                        let _ul = "<ul><label class='checkbox inline'><input type='checkbox' name='group[]' value='"+ this.mId +"' />"+ this.mName +"</label></ul>"
                        $("#my-con").append($(_ul));
                    })
                }else{
                    layer.msg(data.msg,function(){})
                }
            },
            complete : function(xhr, status) {
                myComplete(xhr, status);
            }
        })
    }
    // 添加角色信息
    function addRole(){
        // 防止onblur和onclick发生冲突, 确保onclick先执行
        clearTimeout(roleNameCheckTime);
        let rName = $("input[name='rName']").val().trim();
        let rState = $("input[name='rState']:checked").val().trim();
        var menuIds = "";
        $.each($("input[name='group[]']:checked"), function(){
            menuIds += $(this).val().trim() + "_";
        })
        // 角色名的唯一性验证, 非空
        roleNameCheck(rName);
        setTimeout(function(){
            if(!roleNameCheckFlag){
                return false;
            }
            // 验证没问题, 添加数据
            if(sendAddFlag){
                // 一旦添加即锁死, 防止多次提交
                sendAddFlag = false;
                layer.load(0)
                $.ajax({
                    type: "POST",
                    url: origin + "/role",
					xhrFields: {
					   withCredentials: true
					},
					crossDomain: true,
                    data: {rName:rName,rState:rState,menuIds:menuIds,jwtToken:jwtToken},
                    dataType: "json",
                    success: function (data) {
                        layer.closeAll()
                        if (data.code == 201){
                            layer.msg("添加成功")
                            setTimeout(function(){
                                // 返回index
                                $('#backid').trigger("click");
                            },500)
                        }else{
                            layer.msg(data.msg,function(){})
                        }
                    },
                    complete : function(xhr, status) {
                        myComplete(xhr, status);
                    }
                })
            }
        }, 150)
    }

    $(function () {
        // 查询所有资源信息,遍历生成列表
        queryMenuList()
        $(':checkbox[name="group[]"]').click(function () {
            $(':checkbox', $(this).closest('li')).prop('checked', this.checked);
        });
		$('#backid').click(function(){
				window.location.href="index.html?pageSize=" + globalPageSize + "&pageNum=" + globalPageNum;
        });
    });
</script>